<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <title>DMDirc :: Admin</title>
  <link rel="stylesheet" type="text/css" href="/res/style.css">
 </head>
 <body>
  <div id="container">
   <img id="logo" src="/res/logo.png" alt="DMDirc logo">
   <h1>DMDirc</h1>
<?PHP require_once('admin-menu.php'); ?>
   <div id="content">
    <h2>Referrals</h2>
<?php

 if (isset($_GET['limit'])) {
  $limit = strtotime($_GET['limit']);
  if ($limit == '') { $limit = 0; }
 } else {
  $limit = 0;
 }
 
 if ($limit == 0) {
  $command = 'awk -F\" \'{print $4}\' /etc/apache2/logs/dmdirc.com';
 } else {
  $command = 'cat /etc/apache2/logs/dmdirc.com | awk -F[ \'{print $2}\' | awk -F\" \'{print $1 $4}\'';
 }
 exec($command, $output);
 
 $refs = array();
 $total = 0;
 foreach ($output as $data) {
  if (!isset($_GET['all'])) {
   if (strstr(strtolower($data), 'dmdirc.com') || strstr(strtolower($data), 'dmdirc.co.uk') || strstr(strtolower($data), 'dmdirc.ownage')) {
    continue;
   }
  }
  
  if ($limit == 0) {
   $go = true;
  } else {
   $go = preg_match('/(.*)] (.*)/u', $data, $matches);
  }
  
  if ($go) {
   if ($limit == 0) {
    $ref = $data;
   } else {
    $time = strtotime($matches[1]);
    $ref = $matches[2];
    if ($time < $limit) { continue; }
   }
   
   if ($ref == '-' || strstr($ref, ' ') || empty($ref)) {
    continue; 
   }
   
   $refs[strtolower($ref)]++;
   $total++;
  }
  
 }

 $domains = array();

 foreach ($refs as $url => $count) {
  $parts = parse_url($url);
 
  if (empty($parts['host'])) { continue; }
  if (substr($parts['host'], 0, 4) == 'www.') {
   $parts['host'] = substr($parts['host'], 4);
  }
 
  $domains[$parts['host']][$url] += $count;
 }

 function sum(array $foo) {
  $t = 0;
  foreach ($foo as $v) { $t += $v; }
  return $t;  
 }

 function sortDomains($a, $b) {
  return -1 * strnatcmp(sum($a), sum($b));
 }

 uasort($domains, 'sortDomains');

 echo '<p>There have been ', $total, ' referrals, and a total of ', count($output), ' hits</p>';

 echo '<ul>';

 foreach ($domains as $domain => $urls) {
  arsort($urls);

  echo '<li><strong>', htmlentities($domain), '</strong> - ', sum($urls), ' referrals:<ul>';
  foreach ($urls as $url => $count) {
   $durl = strlen($url) > 70 ? htmlentities(substr($url, 0, 70)) . '&hellip;' : htmlentities($url);
   echo '<li><a href="', htmlentities($url), '">', $durl, '</a> - ', $count, ' referrals</li>'; 
  }
  echo '</ul>';
 }

 echo '</ul>';
?>
   </div>
   <div id="footer">
   </div>
  </div>
 </body>
</html>
